package com.atguigu.common.exception;

import com.atguigu.common.result.R;
import com.atguigu.common.result.ResponseEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;

@Component//交给spring自动管理
@Slf4j
@RestControllerAdvice//在所有以@restController的控制层添加通知 若是@controller需要在方法上添加respBody
public class UnifiedExceptionHandler {


    /*未定义异常*/
    @ExceptionHandler(value = Exception.class)
    public R handlerException(Exception e){
        log.error(e.getMessage(),e);
        return R.error();
    }

    /*特定异常*/
    @ExceptionHandler(value = BadSqlGrammarException.class)
    public R handlerBadSqlGrammarException(BadSqlGrammarException e){
        log.error(e.getMessage(),e);
        return R.setResult(ResponseEnum.BAD_SQL_GRAMMAR_ERROR);
    }
    /*自定义异常*/
    @ExceptionHandler(value = BusinessException.class)
    public R handlerBusinessException(BusinessException e){
        log.error(e.getMessage(),e);
        return R.error().message(e.getMessage()).code(e.getCode());

    }
}
